import Vue from "vue";

import {
	codeToOpenid,
	codeToUserInfo,
	getShareSignature
} from '../api/wx.js'
import {
	getUserInfoByMp
} from '@/api/auth.js'
import cookie from './cookie'
// 引入wechat js-sdk 
const jweixin = require('jweixin-module');

import config from '../config.js'
//  APPID
const APPID = config.wxAppId
// 静默授权 链接
const WX_AUTH_URL = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + APPID +
	'&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_base&state=0#wechat_redirect';

export default {
	//调试模式
	debug: false,
	//权限
	jsApiList: [
		'getLocation',
		'checkJsApi',
		'updateTimelineShareData',
		'updateAppMessageShareData',
		'wx-open-launch-weapp'
	],
	openTagList: ['wx-open-launch-weapp'],
	//判断是否在微信中
	isWechat: function() {
		const ua = window.navigator.userAgent.toLowerCase();
		if (ua.match(/micromessenger/i) == 'micromessenger') {
			console.info('微信浏览器');
			return true;
		} else {
			console.info('非微信浏览器');
			return false;
		}
	},

	//初始化sdk配置
	initJssdk: function(callback, url) {
		if (!this.isWechat()) {
			return;
		}
		getShareSignature().then(res => {
			const data = res.data
			jweixin.config({
				debug: data.debug || this.debug,
				appId: data.appId,
				timestamp: data.wxTimestamp,
				nonceStr: data.wxNoncestr,
				signature: data.wxSignature,
				jsApiList: data.jsApiList || this.jsApiList,
				openTagList: data.openTagList || this.openTagList,
			});
			//配置完成后，再执行分享等功能
			if (typeof callback === 'function') {
				callback(res.data);
			}
		})
	},

	//准备就绪
	ready: function(callback, url) {
		if (!this.isWechat()) {
			return;
		}
		this.initJssdk(function() {
			jweixin.ready(function() {
				//配置完成后，再执行
				if (typeof callback === 'function') {
					callback(jweixin);
				}
			})
		}, url)
	},
	//本次使用的自定义分享的方法  
	share: function(data, url) {
		url = url ? url : window.location.href;
		console.log("url:" + url)
		if (!this.isWechat()) {
			return;
		}
		//每次都需要重新初始化配置，才可以进行分享  
		this.initJssdk(function(signData) {
			console.info(signData)
			jweixin.ready(function() {
				var shareData = {
					title: data && data.title ? data.title : '橘子CPS联盟',
					desc: data && data.desc ? data.desc : '生活全方位高额返佣，一起瓜分千亿市场',
					link: url,
					imgUrl: data && data.img ? data.img :
						'http://mp.tech-harry.cn/static/juzilogo.jpg',
					success: function(res) {
						// 分享后的一些操作,比如分享统计等等
						console.info('分享后的一些操作,比如分享统计等等')
					},
					cancel: function(res) {
						console.info('取消分享')
					}
				};
				//分享给朋友接口  
				jweixin.updateAppMessageShareData(shareData);
				//分享到朋友圈接口  
				jweixin.updateTimelineShareData(shareData);
			});
		}, url);
	},

	closeWindow: function() {
		this.ready(function(wx) {
			wx.closeWindow();
		})
	},

	//在需要定位页面调用
	location: function(success, fail) {
		this.ready(function(wx) {
			wx.getLocation({
				type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
				success: function(res) {
					if (typeof success === 'function') {
						success(res);
					}
				},
				fail: function(res) {
					if (typeof fail === 'function') {
						fail(res);
					}
				}
			});
		});
	},

	// 获取用户openid
	wxAuth: function() {
		// let openid = cookie.get('openid');
		// if (!openid) {
		// 	let code = this.getUrlParam('code');
		// 	if (!code) { //未经过微信授权
		// 		let currentUrl = encodeURIComponent(window.location.href);
		// 		window.location.replace(WX_AUTH_URL.replace('REDIRECT_URI', currentUrl));
		// 	} else {
		// 		codeToOpenid({
		// 			code: code
		// 		}).then(res => {
		// 			openid = res.data
		// 			console.log("授权成功,openid:", openid)
		// 		}).catch(err => {
		// 			console.log("换取openid失败,err:", err);
		// 		});
		// 	}
		// }

		let openid = cookie.get('openid');
		let auth = new Promise((resolve, reject) => {
			if (openid) {
				resolve(openid);
				return;
			}

			let code = this.getUrlParam('code');
			if (!code) { //未经过微信授权
				let currentUrl = encodeURIComponent(window.location.href);
				window.location.replace(WX_AUTH_URL.replace('REDIRECT_URI', currentUrl));
			} else {
				codeToOpenid({
					code: code
				}).then(res => {
					if (res.code == 200) {
						console.log("微信授权完成");
						resolve(res.data);
					} else {
						console.log("换取openid失败");
					}
				});
			}
		});
		auth.then(openid => {
			getUserInfoByMp({
				appid: APPID,
				openid: openid
			}).then(res => {
				if (res.data != null && res.data.token != null) {
					uni.setStorageSync("token", res.data.token)
					uni.setStorageSync("userInfo", res.data.userInfo)
					uni.setStorageSync("isLogin", true)
				}
			})
		})

		return openid;
	},
	getUrlParam: function(key) { //获取当前页面url中的参数
		var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
		var result = window.location.search.substr(1).match(reg);
		return result ? decodeURIComponent(result[2]) : '';
	}
}
